<template>
  <div class="app-container">
    <!-- 查询表单 -->

    <el-row class="search-row" type="flex" justify="space-between">
      <el-col :span="12">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-input v-model="searchObj.roleName"  placeholder="角色名称" style="width: 400px;" @keyup.enter="fetchData()"/>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <el-button type="primary" @click="fetchData()">
        查询
      </el-button>
      <el-button type="default" @click="resetData()">清空</el-button>
      </el-col>
    </el-row>

    <!-- 工具条 -->
    <div>
      <el-button v-if="userinfo&&userinfo.yhlx == 1" type="success" size="mini" @click="addUser()" v-permission="'role.add'">
        添加管理员角色
      </el-button>
      <el-button v-if="userinfo&&userinfo.yhlx == 2" type="success" size="mini" @click="addUser()" v-permission="'role.add'">
        添加员工角色
      </el-button>

      <el-button :disabled="multipleSelection.length === 0" type="danger" size="mini" @click="removeRows()"
        v-permission="'role.remove'">
        批量删除
      </el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border stripe @selection-change="handleSelectionChange"
      :highlight-current-row="true">
      <el-table-column type="selection" width="55" />

      <el-table-column label="序号" width="70" align="center">
        <template #default="{ $index }">
          {{ (page - 1) * limit + $index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="roleName" label="角色名称" align="center" />

      <el-table-column label="操作" width="280" align="center">
        <template #default="{ row }">
          <div class="operation-buttons">

              <el-button type="info" size="mini" v-permission="'role.acl'" @click="$router.push('/acl/role/distribution/' + row.id)" round>
                绑定权限
              </el-button>
              <el-button type="primary" size="mini"  v-permission="'role.update'" @click="$router.push('/acl/role/update/' + row.id)" round>
                修改
              </el-button>
            <el-button type="danger" size="mini"  @click="removeDataById(row.id)"
              v-permission="'role.remove'" round>
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination :current-page="page" :total="total" :page-size="limit" :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center" layout="sizes, prev, pager, next, jumper, ->, total, slot"
      @current-change="fetchData" @size-change="changeSize" />
  </div>
</template>

<script lang="ts" setup>
import roleApi from '@/api/acl/role'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserinfo } from '@/components/Avatar/hooks/useUserinfo'

const { userinfo } = useUserinfo()

const router = useRouter()
const listLoading = ref(true) // 数据是否正在加载
const list = ref(null) // 讲师列表
const total = ref(0) // 数据库中的总记录数
const page = ref(1) // 默认页码
const limit = ref(5) // 每页记录数
const searchObj = ref({}) // 查询表单对象
const multipleSelection = ref([]) // 批量选择中选择的记录列表

const changeSize = size => {
  console.log(size)
  limit.value = size
  fetchData(1)
}

const addUser = () => {
  router.push('/acl/role/add')
}

// 加载讲师列表数据
const fetchData = (p = 1) => {
  // 异步获取远程数据（ajax）
  page.value = p

  roleApi
    .getPageList(page.value, limit.value, searchObj.value)
    .then(response => {
      list.value = response.data.items
      total.value = response.data.total
      listLoading.value = false
    })
    .catch(error => {
      console.log(error)
      listLoading.value = false
    })
}
const resetData = () => {
  searchObj.value = {}
  fetchData()
}

// 根据id删除数据
const removeDataById = id => {
  ElMessageBox.confirm('确定删除选中的记录吗?', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      console.log('yyyyyyy删除aaaaaaaaaaaaaa')
      roleApi
        .removeById(id)
        .then(response => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData()
        })
        .catch(error => {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

// 批量删除
const removeRows = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage({
      message: '请选择要删除的记录',
      type: 'warning',
    })
    return
  }

  const ids = multipleSelection.value.map(item => item.id)

  ElMessageBox.confirm(`确定删除选中 ${ids.length} 条记录吗?`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      roleApi
        .removeRows(ids)
        .then(response => {
          ElMessage({
            type: 'success',
            message: '删除成功!',
          })

          // 如果删除了最后一页的记录，则需要自动跳转到上一页
          if (list.value.length === 1 && page.value > 1) {
            fetchData(page.value - 1)
          } else {
            fetchData()
          }

          // 清空选择列表
          multipleSelection.value = []
        })
        .catch(error => {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

// 处理批量选择事件
const handleSelectionChange = val => {
  multipleSelection.value = val
}

fetchData()
</script>
<style scoped>
.operation-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
</style>